package com.googlecode.mvcguice.view;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Andrey Vityuk
 */
public class ServletBinding {
	private final Map<String, Object> variables = new HashMap<String, Object>();

	@SuppressWarnings("unchecked")
	public ServletBinding(HttpServletRequest request) {
		/*
		 * Bind request parameters
		 */
		final Map<String, String[]> requestParams = request.getParameterMap();
		final Map<String, Object> params = new HashMap<String, Object>(requestParams.size());
		for (Entry<String, String[]> e : requestParams.entrySet()) {
			final String name = e.getKey();
			final String[] values = e.getValue();

			if (!variables.containsKey(name)) {
				if (values.length == 1) {
					params.put(name, values[0]);
				} else {
					params.put(name, values);
				}
			}
		}
		setVariable("params", params);

		/*
		 * Bind attributes
		 */
		for (Enumeration<String> names = request.getAttributeNames(); names.hasMoreElements();) {
			String name = names.nextElement();
			setVariable(name, request.getAttribute(name));
		}
	}

	public void setVariable(String name, Object value) {
		variables.put(name, value);
	}

	public boolean hasVariable(String name) {
		return variables.containsKey(name);
	}

	public Map<String, Object> getVariables() {
		return variables;
	}
}
